package cn.zhangfusheng.elasticsearch.jexl.analysis.impl;

import cn.zhangfusheng.elasticsearch.exception.GlobalSystemException;
import cn.zhangfusheng.elasticsearch.jexl.Jexl3Execute;
import cn.zhangfusheng.elasticsearch.jexl.Jexl3Util;
import cn.zhangfusheng.elasticsearch.jexl.analysis.Analysis;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author fusheng.zhang
 * @date 2022-03-08 10:30:03
 */
@Data
@AllArgsConstructor
public class VariableAnalysis implements Analysis {

    /**
     * 变量文本
     */
    private String variableStr;

    @Override
    public String toString() {
        return variableStr;
    }

    @Override
    public void execute(Jexl3Execute jexl3Execute) {
        Object o = Jexl3Util.execute(jexl3Execute.getParams(), jexl3Execute.getConstantParams(), Jexl3Util.toStr(variableStr));
        if (Objects.nonNull(o)) {
            if ((o instanceof Collection) || (o.getClass().isArray() && o.getClass() != byte[].class)) {
                Collection<?> collection = Jexl3Util.asCollection(o);
                if (collection.isEmpty()) {
                    jexl3Execute.setStr("NULL");
                } else {
                    collection.forEach(jexl3Execute::setValue);
                    jexl3Execute.setStr(collection.stream().map(c -> "?").collect(Collectors.joining(",")));
                }
            } else {
                jexl3Execute.setValue(o).setStr("?");
            }
        } else {
            throw new GlobalSystemException("{} value is empty", variableStr);
        }
    }
}
